package loengud.w04;

/*
 * It's preferred to import single classes
 * not the whole package using '*'.
 * 
 * Instead of
 * 
 * import java.io.*;
 * 
 * we should import:
 * 
 * import java.io.IOException;
 * import java.io.FileWriter;
 * etc.
 */
import java.io.*;
import java.util.*;

/**
 * An example class for reversing numbers in file.
 * @author Ago
 *
 */
public class ReverseFile {
	/**
	 * Main method.
	 * @param args Arguments from command line
	 */
	public static void main(String[] args) {
		/*
		 * Change the locale to US,
		 * otherwise the default for my computer
		 * is Estonian, which treats numbers
		 * with commas (4,5). US locale uses
		 * point (4.5).
		 */
		Locale.setDefault(Locale.US);
		Scanner data;
		PrintWriter result;
		double[] number = new double[10];
		int numberCt;
		try {
			// input stream
			// file name is relative to the working directory.
			// in Eclipse, the working dir is project root.
			data = new Scanner(
					new FileReader("2013/src/loengud/w04/data.dat"));
		} catch (FileNotFoundException e) {
			System.out.println("Can't find file data.dat!");
			return; // end the program
		}
		try { // create the output stream
			result = new PrintWriter(new FileWriter("2013/src/loengud/w04/result.dat"));
		} catch (IOException e) {
			System.out.println("Can't open file result.dat!");
			System.out.println(e.toString());
			data.close(); // close the input file
			return; // end the program
		}
		try {
			// read the data from the input file,
			numberCt = 0;
			while (data.hasNext()) {
				// let's read double until there 
				// is something to read
				number[numberCt] = data.nextDouble();
				numberCt++;
			}
			// then output the numbers in reverse order
			for (int i = numberCt - 1; i >= 0; i--) {
				result.println(number[i]);
			}
			System.out.println("Done!");
		} catch (InputMismatchException e) {
			// input is not a double
			System.out.println("Parsing error: " + e.getMessage());
		} catch (IndexOutOfBoundsException e) {
			// our array is too short for all the numbers
			System.out.println("Too many numbers in data file.");
			System.out.println("Processing has been aborted.");
		} finally {
			// let's close input and output files
			data.close();
			result.close();
		}
	} // end of main()
} // end of class

